import { Response } from 'express';
import { logger } from './logger';

/**
 * API响应工具类
 */
export class ApiResponse {
  /**
   * 发送成功响应
   */
  static success<T>(res: Response, data: T, message?: string) {
    const response = {
      success: true,
      data,
      ...(message && { message })
    };

    logger.info('API response', {
      path: res.req.path,
      status: 200,
      response
    });

    return res.json(response);
  }

  /**
   * 发送分页数据响应
   */
  static page<T>(res: Response, {
    data,
    total,
    page,
    pageSize
  }: {
    data: T[];
    total: number;
    page: number;
    pageSize: number;
  }) {
    const response = {
      success: true,
      data,
      pagination: {
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      }
    };

    logger.info('API response', {
      path: res.req.path,
      status: 200,
      response
    });

    return res.json(response);
  }

  /**
   * 发送创建成功响应
   */
  static created<T>(res: Response, data: T, message = '创建成功') {
    const response = {
      success: true,
      message,
      data
    };

    logger.info('API response', {
      path: res.req.path,
      status: 201,
      response
    });

    return res.status(201).json(response);
  }

  /**
   * 发送更新成功响应
   */
  static updated(res: Response, message = '更新成功') {
    const response = {
      success: true,
      message
    };

    logger.info('API response', {
      path: res.req.path,
      status: 200,
      response
    });

    return res.json(response);
  }

  /**
   * 发送删除成功响应
   */
  static deleted(res: Response, message = '删除成功') {
    const response = {
      success: true,
      message
    };

    logger.info('API response', {
      path: res.req.path,
      status: 200,
      response
    });

    return res.json(response);
  }

  /**
   * 发送无内容响应
   */
  static noContent(res: Response) {
    logger.info('API response', {
      path: res.req.path,
      status: 204
    });

    return res.status(204).send();
  }
}
